package com.wisdudu.frame.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;

import com.orhanobut.logger.Logger;
import com.wisdudu.frame.R;

import java.util.List;

/**
 * Created by qyf on 2016/8/11.
 */

public abstract class BaseFragmentActivity extends BaseActivity {
//    private int index = 0;

    //    private HashMap<Integer,String> fragmentIndexes=new HashMap<>();
    //获取根目录的fragment
    protected abstract BaseFragment getRootFragment();

    //获取Intent
    protected void handleIntent(Intent intent) {

    }

    //布局文件ID
    protected int getContentViewId() {
        return R.layout.activity_multi_base;
    }

    //布局中Fragment的ID
    protected int getFragmentContentId() {
        return R.id.fl_base_content;
    }

    //添加fragment
    protected void addFragment(Fragment current, BaseFragment added) {
//        if (fragment != null) {
//            getFragmentManager().beginTransaction()
//                    .replace(getFragmentContentId(), fragment, fragment.getClass().getSimpleName())
//                    .addToBackStack(fragment.getClass().getSimpleName())
//                    .commitAllowingStateLoss();
//        }

        if (added != null) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction()
                    .add(getFragmentContentId(), added, added.getClass().getSimpleName())
                    .addToBackStack(added.getClass().getSimpleName());
            if (current != null) {
                fragmentTransaction.hide(current);
            }
            fragmentTransaction.commitAllowingStateLoss();
//            Logger.d("添加后容器容量：%s", getSupportFragmentManager().getBackStackEntryCount());
//            fragmentIndexes.put(++index,added.getClass().getSimpleName());
        }
    }


    //移除fragment
    protected void removeFragment() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            Fragment previous = getSupportFragmentManager().getFragments()
                    .get(getSupportFragmentManager().getBackStackEntryCount() - 2);
            getSupportFragmentManager().beginTransaction().show(previous).commitAllowingStateLoss();
            getSupportFragmentManager().popBackStack();
        } else {
            finish();
            Logger.d("finish");
        }
    }

    //返回键返回事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
//            Logger.d("当前回退栈容量：%s", getSupportFragmentManager().getBackStackEntryCount());
            if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
                finish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentViewId());
        if (null != getIntent()) {
            handleIntent(getIntent());
        }
        //避免重复添加Fragment
        if (getFragmentManager().getBackStackEntryCount() < 1) {
            BaseFragment firstFragment = getRootFragment();
            if (null != firstFragment) {
                addFragment(null, firstFragment);
            }
        }

    }

    public void addAndRemoveFragment(int removeCount, BaseFragment fragment) {
//        Logger.d("add and remove fragment,%s", fragment.getClass().getSimpleName());
        if (removeCount > getSupportFragmentManager().getBackStackEntryCount() - 1) {
            throw new RuntimeException("removeCount out of index,maybe you ready to remove root fragment ,that't not allowed!");
        } else {
            List<Fragment> fragments = getSupportFragmentManager().getFragments();

            for (int i = 0; i < fragments.size(); i++) {
//                Logger.d("add and remove fragment for:%s", fragments.get(i).getClass().getSimpleName());
            }
            Fragment previous = getSupportFragmentManager().getFragments()
                    .get(getSupportFragmentManager().getBackStackEntryCount() - removeCount-1);
//            Logger.d("add and remove fragment previous:%s", previous.getClass().getSimpleName());

            for (int i = 0; i < removeCount; i++) {
                getSupportFragmentManager().popBackStack();
//                Logger.d("循环次数");
            }
            addFragment(previous, fragment);
        }
    }

//    /**
//     * 移除某tag对应Fragment，注意add后调用
//     * @param tag
//     */
//    public void removeFragment(String tag) {
//        Logger.i("移除对应Fragment:%s",tag);
//        FragmentManager fragmentManager = getFragmentManager();
//        Fragment fragmentByTag = fragmentManager.findFragmentByTag(tag);
//        if(fragmentByTag!=null){
//            Logger.d("真正移除吗？");
//            fragmentManager.beginTransaction().remove(fragmentByTag).commit();
//        }
//    }


//
//    private FragmentStack mFragmentStack;
//    private SparseArray<RequestFragmentsRecord> requestFragments = new SparseArray<>();
//
//    public <T extends BaseFragment> void push(String tag, Class<T> classType, Bundle args) {
//        mFragmentStack.push(tag, classType, args, null);
//    }
//
//    public <T extends BaseFragment> void pushForResult(String originalTag, int requestCode, String fragmentTag, Class<T> classType, Bundle args) {
//        addRequestToRecord(originalTag, requestCode);
//        mFragmentStack.push(fragmentTag, classType, args, requestCode);
//    }
//
//    public boolean pop() {
//        return mFragmentStack.pop();
//    }
//
//    public com.wisdudu.blank.support.base.BaseFragment get(String tag) {
//        return mFragmentStack.get(tag);
//    }
//
//    public Fragment getFragmentTopInStack() {
//        return mFragmentStack.getFragmentTopInStack();
//    }
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        int containerId = onCreateContainer();
//        mFragmentStack = new FragmentStack(getFragmentManager(), containerId);
//        if (savedInstanceState != null) {
//            mFragmentStack.restoreStack(savedInstanceState);
//            ArrayList<RequestFragmentsRecord> restoreRequestFragments = savedInstanceState.getParcelableArrayList("__requestFragments");
//            for (RequestFragmentsRecord requestFragment : restoreRequestFragments) {
//                requestFragments.setValueAt(requestFragment.requestCode, requestFragment);
//            }
//        }
//        afterOnCreate(savedInstanceState);
//    }
//
//    /**
//     * 部分onCreate中在setContentView后的代码，也可以在onCreateContainer()中创建
//     */
//    protected void afterOnCreate(Bundle savedInstanceState) {
//    }
//
//    /**
//     * @return 返回的是FramLayout的id, 如果有复杂布局，可以重写，但是注意setContentView()
//     */
//    protected int onCreateContainer() {
//        setContentView(R.layout.activity_multi_base);
//        return R.id.fl_base_content;
//    }
//
//    /**
//     * 根据activity实例，获取toolbar,设置标题，菜单，菜单项监听等
//     * @param title 标题
//     * @return toolbar实例
//     */
//    public Toolbar initToolbar(CharSequence title) {
//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
//        ActionBar actionBar = getSupportActionBar();
//        actionBar.setTitle(title);
//        if (actionBar != null) {
//            actionBar.setDisplayHomeAsUpEnabled(true);
//        }
//        return toolbar;
//    }
//    public Toolbar initToolbar(@StringRes int title) {
//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
//        ActionBar actionBar = getSupportActionBar();
//        actionBar.setTitle(title);
//        if (actionBar != null) {
//            actionBar.setDisplayHomeAsUpEnabled(true);
//        }
//        return toolbar;
//    }
//
//    @CallSuper
//    protected void onSaveInstanceState(Bundle outState) {
//        if (outState != null) {
//            outState.putParcelableArrayList("__requestFragments", asList(requestFragments));
//        }
//        super.onSaveInstanceState(outState);
//    }
//
//    /**
//     * 没有的置为null
//     *
//     * @param fragmentTag
//     * @param intent      ,可null
//     * @param requestCode
//     * @param options
//     */
//    public void startActivityForResult(@NonNull String fragmentTag, @Nullable Intent intent, @NonNull int requestCode, @Nullable Bundle options) {
//        addRequestToRecord(fragmentTag, requestCode);
//        super.startActivityForResult(intent, requestCode, options);
//    }
//
//    @CallSuper
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        RequestFragmentsRecord reqs = requestFragments.get(requestCode);
//        if (reqs != null) {
//            if (--requestFragments.get(requestCode).reqCount == 0) {
//                requestFragments.remove(requestCode);
//            }
//
//            boolean found = false;
//            for (String tag : reqs.tags) {
//                Fragment fragment = mFragmentStack.get(tag);
//                if (fragment instanceof com.wisdudu.blank.support.base.BaseFragment) {
//                    ((com.wisdudu.blank.support.base.BaseFragment) fragment).onResult(requestCode, resultCode, data);
//                    found = true;
//                }
//            }
//            if (!found) requestFragments.remove(requestCode);
//        }
//        super.onActivityResult(requestCode, resultCode, data);
//    }
//
//    @CallSuper
//    @Override
//    public void onBackPressed() {
//        super.onBackPressed();
//        do {
//            Fragment topFragment = mFragmentStack.getFragmentTopInStack();
//            if (topFragment instanceof com.wisdudu.blank.support.base.BaseFragment) {
//                if (((com.wisdudu.blank.support.base.BaseFragment) topFragment).onBackPressed()) {
//                    break;
//                }
//            }
//            if (mFragmentStack.pop()) break;
//            finish();
//        } while (false);
//    }
//
//    private void addRequestToRecord(String fragmentTag, int requestCode) {
//        if (requestFragments.get(requestCode) == null) {
//            ArrayList<String> fragmentTags = new ArrayList<>();
//            fragmentTags.add(fragmentTag);
//            requestFragments.setValueAt(requestCode, new RequestFragmentsRecord(1, fragmentTags, requestCode));
//        } else {
//            requestFragments.get(requestCode).reqCount++;
//            requestFragments.get(requestCode).tags.add(fragmentTag);
//        }
//    }
//
//    class FragmentStack {
//        private FragmentActivity mActivity;
//        private int containerId;
//        private FragmentManager mFragmentManager;
//
//        private ArrayList<String> fragmentStackRecord = new ArrayList<>();
//        private HashMap<String, Fragment> fragments = new HashMap<>();
//        private long curSystemTime = 0L;
//        private long PUSH_INTERVAL = 500L;
//
//        public FragmentStack(FragmentManager fragmentManager, int containerId) {
//            mActivity = BaseFragmentActivity.this;
//            mFragmentManager = fragmentManager;
//            this.containerId = containerId;
//        }
//
//        void saveStack(Bundle outState) {
//            if (outState != null) {
//                outState.putStringArrayList("__fragmentRecord", fragmentStackRecord);
//            }
//        }
//
//        void restoreStack(Bundle savedInstanceState) {
//            fragmentStackRecord.clear();
//            fragmentStackRecord.addAll(savedInstanceState.getStringArrayList("__fragmentRecord"));
//
//            FragmentTransaction trans = mFragmentManager.beginTransaction();
//            boolean showFlag = false;
//            for (String tag : fragmentStackRecord) {
//                Fragment fragment = mFragmentManager.findFragmentByTag(tag);
//
//                if (showFlag) {
//                    trans.hide(fragment);
//                } else {
//                    trans.show(fragment);
//                    showFlag = true;
//                }
//                fragments.put(tag, ((com.wisdudu.blank.support.base.BaseFragment) fragment));
//            }
//            trans.commit();
//        }
//
//        <T> void push(String tag, Class<T> classType, Bundle args, Integer requestCode) {
//            long time = System.currentTimeMillis();
//
//            Fragment fragment = mFragmentManager.findFragmentByTag(tag);
//            if (fragment != null) {
//                curSystemTime = time;
//                return;
//            }
//            if (time - curSystemTime < PUSH_INTERVAL) {
//                curSystemTime = time;
//                return;
//            }
//            curSystemTime = time;
//            FragmentTransaction trans = mFragmentManager.beginTransaction();
//
//            Fragment topFragment = getFragmentTopInStack();
//            if (topFragment != null) {
//                trans.hide(topFragment);
//            }
//            String className = classType.getCanonicalName();
//            fragment = Fragment.instantiate(mActivity, className, args);
//            trans.add(containerId, fragment, tag);
//            if (requestCode != null) {
//                ((com.wisdudu.blank.support.base.BaseFragment) fragment).mRequestInfo = new RequestInfo(requestCode, 0, null);
//            }
//            fragments.put(tag, fragment);
//            fragmentStackRecord.add(tag);
//            trans.addToBackStack(tag).commit();
//        }
//
//        boolean pop() {
//            int count = mFragmentManager.getBackStackEntryCount();
//            if (count > 1) {
//                String tag = fragmentStackRecord.get(fragmentStackRecord.size() - 1);
//                RequestInfo reqInfo = get(tag).mRequestInfo;
//                if (reqInfo != null) {
////                    activity.onActivityResult(reqInfo.requestCode, reqInfo.resultCode, reqInfo.resultData)
//                }
//                fragmentStackRecord.remove(tag);
//                fragments.remove(tag);
//                mFragmentManager.popBackStack();
//                return true;
//            } else {
//                return false;
//            }
//        }
//
//        private com.wisdudu.blank.support.base.BaseFragment get(String tag) {
//            return (com.wisdudu.blank.support.base.BaseFragment) fragments.get(tag);
//        }
//
//        private Fragment getFragmentTopInStack() {
//            int count = mFragmentManager.getBackStackEntryCount();
//            if (count > 0) {
//                String tag = mFragmentManager.getBackStackEntryAt(count - 1).getName();
//                return mFragmentManager.findFragmentByTag(tag);
//            }
//            return null;
//        }
//    }
//
//
//    private <RequestFragmentsRecord> ArrayList<RequestFragmentsRecord> asList(SparseArray<RequestFragmentsRecord> sparseArray) {
//        if (sparseArray == null) return null;
//        ArrayList<RequestFragmentsRecord> arrayList = new ArrayList<RequestFragmentsRecord>(sparseArray.size());
//        for (int i = 0; i < sparseArray.size(); i++)
//            arrayList.add(sparseArray.valueAt(i));
//        return arrayList;
//    }
}
